# -*- coding: UTF-8 -*-
"""
@auth:buxiangjie
@date:2022/2/24 16:56
@describe: 
"""
from common.common_func import Common
from common.db_operate.db_operate import Saas
from assertpy.assertpy import soft_assertions, assert_that
from collections import defaultdict
import datetime

swap_data = Common.get_json_data("data", "asset_swap_apply.json")
swap_detail_data = Common.get_json_data("data", "asset_swap_detail.json")

swap_detail_data_by_apply_id = defaultdict(list)
for detail in swap_detail_data:
	swap_detail_data_by_apply_id[str(detail["swapApplyId"])].append(detail)
#
# asset_id_list = []
# for ass in swap_data:
# 	asset_id_list.append(ass["assetId"])
# print(set(asset_id_list))


# 校验apply与detail中的金额是否一致
excep_apply = []
count = 0
for apply in swap_data:
	apply_amount = apply["successAmount"]
	detail_amount = 0.0
	for detail in swap_detail_data_by_apply_id[str(apply["id"])]:
		detail_amount += detail["actionAmount"]
	detail_amount = round(detail_amount, 2)
	try:
		# print(
		# 	f"""
		# 	apply:{apply["id"]} amount:{apply_amount}
		# 	detail:{detail["id"]} amount:{detail_amount}
		# """
		# )
		assert_that(apply_amount).is_equal_to(detail_amount)
	except Exception:
		excep_apply.append(apply["id"])

print(f"异常申请列表:{excep_apply}")

cleared_excep_data = []
no_cleared_excep_data = []

for d in swap_detail_data:
	d["env"] = "prod"
	if d["planCategory"] > 2:
		pass
	else:
		repayment_plan_data = Saas().get_repayment_plan_data(**d)
		if repayment_plan_data["repayment_status"] == 3:
			# 本息计划已结清校验
			pay_time = datetime.datetime.strptime(repayment_plan_data["pay_time"], '%Y-%m-%d %H:%M:%S')
			swap_time = datetime.datetime.strptime(d["actionTime"], '%Y-%m-%d %H:%M:%S')
			if swap_time > pay_time:
				# 债转在还款之后
				try:
					assert_that(d["actionAmount"]).is_equal_to(repayment_plan_data["rest_amount"])
				except Exception:
					cleared_excep_data.append(
						{
							"asset_id": repayment_plan_data["asset_id"],
							"plan_id": repayment_plan_data["id"]
						}
					)
			else:
				# 债转在还款之前
				try:
					assert_that(d["actionAmount"]).is_equal_to(repayment_plan_data["cur_amount"])
				except Exception:
					cleared_excep_data.append(
						{
							"asset_id": repayment_plan_data["asset_id"],
							"plan_id": repayment_plan_data["id"]
						}
					)
		else:
			# 本息计划未结清校验
			try:
				assert_that(d["actionAmount"]).is_equal_to(repayment_plan_data["rest_amount"])
			except Exception:
				no_cleared_excep_data.append(
					{
						"asset_id": repayment_plan_data["asset_id"],
						"plan_id": repayment_plan_data["id"]
					}
				)
print(f"已结清异常数据:{cleared_excep_data}")
print(f"未结清异常数据:{no_cleared_excep_data}")